package com.sysu.simulation.fragments.sim;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sysu.simulation.BaseFragment;
import com.sysu.simulation.R;
import com.sysu.simulation.SimFragment;
import com.sysu.simulation.adapter.BaseRecyclerAdapter;
import com.sysu.simulation.adapter.SimClothesAdapter;
import com.sysu.simulation.bean.Clothes;
import com.sysu.simulation.bean.ListResult;
import com.sysu.simulation.bean.SimParams;
import com.sysu.simulation.helper.AccountHelper;
import com.sysu.simulation.helper.ApiHelper;
import com.sysu.simulation.helper.CacheHelper;
import com.sysu.simulation.helper.NetworkHelper;
import com.sysu.simulation.interfaces.SeriesFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cz.msebera.android.httpclient.Header;

public class SimClothesFragment extends BaseFragment implements SimClothesAdapter.OnFooterClickListener,
        BaseRecyclerAdapter.OnItemClickListener, SeriesFragment, SimFragment.SimParamsSetter{

    @BindView(R.id.sim_clothes_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.sim_material)
    Spinner mMaterial;
    @BindView(R.id.sim_thickness)
    Spinner mThickness;
    @BindView(R.id.sim_type)
    Spinner mType;
    @BindView(R.id.selected_clothes_list)
    ListView selected_list;
    @BindView(R.id.select_sim_clothes)
    Button select_button;

    private SimClothesAdapter mAdapter;
    protected TextHttpResponseHandler mHandler;
    private ListResult<Clothes> mDatas;
    private static final String CLOTHES_KEY_NAME = "clothes";
    private List<Clothes> mSelected;
    private SelectedClothesAdapter mSelectedAdapter;

    public SimClothesFragment() {
        // Required empty public constructor
    }

    public static SimClothesFragment newInstance() {
        return new SimClothesFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_sim_clothes;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mAdapter = new SimClothesAdapter(getContext());
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnFooterClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
        GridLayoutManager gm = new GridLayoutManager(mContext, 2, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(gm);

        ArrayAdapter<Clothes.Material> materialAdapter = new ArrayAdapter<>(mContext, R.layout.support_simple_spinner_dropdown_item, Clothes.Material.values());
        ArrayAdapter<Clothes.Thickness> thicknessAdapter = new ArrayAdapter<>(mContext, R.layout.support_simple_spinner_dropdown_item, Clothes.Thickness.values());
        ArrayAdapter<Clothes.Type> typeAdapter = new ArrayAdapter<>(mContext, R.layout.support_simple_spinner_dropdown_item, Clothes.Type.values());
        mMaterial.setAdapter(materialAdapter);
        mThickness.setAdapter(thicknessAdapter);
        mType.setAdapter(typeAdapter);

        mSelected = new ArrayList<>();
        mSelectedAdapter = new SelectedClothesAdapter();
        selected_list.setAdapter(mSelectedAdapter);
        select_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Clothes sc = new Clothes();
                sc.setMaterial((Clothes.Material)mMaterial.getSelectedItem());
                sc.setThickness((Clothes.Thickness)mThickness.getSelectedItem());
                sc.setType((Clothes.Type)mType.getSelectedItem());
                mSelected.add(sc);
                mSelectedAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        mDatas = new ListResult<>();
        mHandler = new TextHttpResponseHandler() {

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    ListResult<Clothes> results = new Gson().fromJson(responseString, new TypeToken<ListResult<Clothes>>(){}.getType());
                    if (results != null && results.getItems() != null) {
                        if(results.getItems().size()==0)
                            Toast.makeText(mContext,"没有更多服装了",Toast.LENGTH_SHORT).show();
                        setAdapterData(results);
                    } else {
                        Toast.makeText(mContext,"没有更多服装了",Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(statusCode, headers, responseString, e);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                onComplete();
            }

            @Override
            public void onCancel() {
                super.onCancel();
                onComplete();
            }
        };

        List<Clothes> items = CacheHelper.load(mContext, new TypeToken<List<Clothes>>(){}.getType(), CLOTHES_KEY_NAME);
        if(items == null) {
            mDatas.setItems(new ArrayList<Clothes>());
        }
        else {
            mDatas.setItems(items);
            mAdapter.addItems(mDatas.getItems());
        }
        mDatas.setNextItem(0);
        requestData();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void requestData() {
        if(NetworkHelper.hasInternet(mContext)) {
            ApiHelper.getUserClothes(AccountHelper.getUserId(), mDatas.getNextItem(), mHandler);
        }
        else {
            Toast.makeText(mContext,"未连接网络",Toast.LENGTH_SHORT).show();
        }
    }

    private void setAdapterData(ListResult<Clothes> results) {
        if(mDatas.getNextItem()==0) {
            mDatas.setItems(results.getItems());
            mAdapter.clear();
            mAdapter.addItems(mDatas.getItems());
            CacheHelper.save(mContext, mDatas.getItems(), CLOTHES_KEY_NAME);
        }
        else {
            mAdapter.addItems(results.getItems());
        }
        mDatas.setNextItem(results.getNextItem());
    }

    private void onComplete() {}

    @Override
    public void onItemClick(int position, long itemId) {
        Clothes item = mAdapter.getItem(position);
        mMaterial.setSelection(item.getMaterial().ordinal());
        mThickness.setSelection(item.getThickness().ordinal());
        mType.setSelection(item.getType().ordinal());
        //mAdapter.setSelectedItem(position, 0);
    }

    @Override
    public void onFooterClick() {
        requestData();
    }

    @Override
    public String getPreviousPage() {
        return SimBodyFragment.class.getName();
    }

    @Override
    public String getNextPage() {
        return SimStageFragment.class.getName();
    }

    @Override
    public String getNavTitle() {
        return "服装设置";
    }

    @Override
    public Boolean canMoveForward() {
        int upperCount = 0;
        for(Clothes clothes : mSelected) {
            if(clothes.getType().ordinal()<3) upperCount++;
        }
        if(upperCount==0 || upperCount==mSelected.size()) {
            Toast.makeText(mContext, "至少选择一件下衣和上衣", Toast.LENGTH_SHORT).show();
            return false;
        }
        else return true;
    }

    @Override
    public void setParams(SimParams params) {
        params.setClothes(mSelected);
    }

    private class SelectedClothesAdapter extends BaseAdapter {
        private TextView sMaterial, sThickness, sType;

        private SelectedClothesAdapter() {
            super();
        }

        @Override
        public int getCount() {
            return mSelected.size();
        }

        @Override
        public Object getItem(int i) {
            return mSelected.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            if(view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.item_selected_clothes,null);
                ImageView deselect = (ImageView) view.findViewById(R.id.deselect_clothes);
                deselect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mSelected.remove(i);
                        mSelectedAdapter.notifyDataSetChanged();
                    }
                });
            }

            sMaterial = (TextView) view.findViewById(R.id.selected_material);
            sThickness = (TextView) view.findViewById(R.id.selected_thickness);
            sType = (TextView) view.findViewById(R.id.selected_type);

            sMaterial.setText(mSelected.get(i).getMaterial().toString());
            sThickness.setText(mSelected.get(i).getThickness().toString());
            sType.setText(mSelected.get(i).getType().toString());

            return view;
        }
    }
}
